package org.example.web;


import com.example.fanqie.entity.Author;
import com.example.fanqie.entity.Category;
import com.example.fanqie.entity.Chapter;
import com.example.fanqie.entity.Novel;
import com.example.fanqie.mapper.AuthorMapper;
import com.example.fanqie.mapper.CategoryMapper;
import com.example.fanqie.mapper.ChapterMapper;
import com.example.fanqie.mapper.NovelMapper;
import org.example.util.LuceneIndexerutil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.ParseException;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@RestController
@RequestMapping("lucene")
public class LuceneDao {


    @Resource
    private NovelMapper novelMapper;

    @Resource
    private AuthorMapper authorMapper;
    @Resource
    private CategoryMapper categoryMapper;

    @Resource
    private ChapterMapper chapterMapper;
    @Resource
    private  LuceneIndexerutil luceneIndexerutil;


    @RequestMapping("/indexLucene")
    public void indexLucene() throws IOException {
        List<Novel> novels = novelMapper.selectnovel();
        for (Novel n : novels) {

            Author author = authorMapper.selectauthorId(n.getAuthorId());
            Category category = categoryMapper.selectcategoryId(n.getCategoryId());
            n.setAuthorName(author.getAuthorName());
            n.setCategoryName(category.getCategoryName());
            List<Chapter> selectchapterlist = chapterMapper.selectchapterlist(n.getNovelId());
            if(selectchapterlist.size() > 0){
                n.setChapterTitle(selectchapterlist.get(selectchapterlist.size() - 1).getChapterTitle());
                n.setPublishDatezuixin(selectchapterlist.get(selectchapterlist.size() - 1).getPublishDate());
                n.setChapterId(selectchapterlist.get(selectchapterlist.size() - 1).getChapterId());
                AtomicInteger x = new AtomicInteger(0);
                selectchapterlist.forEach(chapter -> {
                    x.addAndGet(chapter.getCount());
                });
                n.setWordCount(x.get());
            }

        }
        System.out.println(novels.get(0));


        luceneIndexerutil.indexNovel(novels);

    }

    @RequestMapping("/searchLucene")
    public List<Novel> searchLucene(@RequestParam("selectneirou") String keyword) throws IOException, ParseException {

        List<Novel> novels = luceneIndexerutil.searchNovel(keyword);
        return novels;

    }



}
